//
//  CZPullDownToRefreshControl.swift
//  CZWeibo
//
//  Created by 周振兰 on 16/5/23.
//  Copyright © 2016年 周振兰. All rights reserved.
//

import UIKit
///高度
private let CZPullDownToRefreshControlHeight:CGFloat = 60

///定义三种状态
enum  CZPullDownToRefreshStatus {
    case Normal  //箭头朝下，下拉刷新
    case Pulling  //箭头朝上，释放刷新
    case Refreshing //转轮刷新，正在刷新
}

///下拉刷新控件

class CZPullDownToRefreshControl: UIView {

    
    
  ///记录当前状态
    private var currentStatus:CZPullDownToRefreshStatus = CZPullDownToRefreshStatus.Normal {
        
        didSet{
            //状态切换后调用，根据状态设置view的内容
            
            switch currentStatus {
            case .Normal :
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                
            case .Pulling :
                
                messageLabel.text = "CZDefaultDuration"
                UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing :
                
                // 隐藏箭头,显示风火轮,文字 正在刷新...
                self.arrowView.hidden = true
                self.flvView.hidden  = false
                messageLabel.text = "正在刷新"
                //风火轮转起来
                let rotationAnim = CABasicAnimation(keyPath: "transform.rotation")
                rotationAnim.toValue = M_PI * 2
                rotationAnim.duration = CZDefaultDuration
                rotationAnim.repeatCount = MAXFLOAT
                rotationAnim.removedOnCompletion = false
                
                //开始动画
                flvView.layer.addAnimation(rotationAnim, forKey: nil)
                
                 // 下拉刷新控件显示出来,修改contentInset.top,在原有的基础上添加下拉刷新控件的高度
                
                UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                    self.superScollView?.contentInset.top += CZPullDownToRefreshControlHeight
                    
                })
            }
            
            
        }
        
        
    }
    
    let NormalToPullingOffset:CGFloat  = -124
    
    
    
    ///父控件
    private var superScollView:UIScrollView?
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: -CZPullDownToRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: CZPullDownToRefreshControlHeight)
        super.init(frame: newFrame)
        
        prepareUI()
    }
     // 在下拉刷新控件销毁的时候移除监听
    
    deinit {
         // 监听谁的属性,就用谁来移除
        superScollView?.removeObserver(self, forKeyPath: "contentOffset")
        
    }

    func prepareUI()
    {
//        backgroundColor = UIColor.yellowColor()
        //隐藏烽火轮
        flvView.hidden = true

        
        //添加子控件
        addSubview(arrowView)
        addSubview(flvView)
        addSubview(messageLabel)
        
        //添加约束
        //箭头
        arrowView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        ///风火轮和箭头重合
        flvView.snp_makeConstraints { (make) -> Void in
            make.centerX.centerY.equalTo(arrowView)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowView.snp_trailing).offset(10)
            make.centerY.equalTo(self)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if let superScollView = newSuperview as? UIScrollView {
             // 判断父控件是否是UIScrollView或其子控件
            self.superScollView = superScollView
            //KVO监察对象的改变
            superScollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
            
        }

    }
    //  KVO监听到了superScrollView的contentOffset的改变
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        用户拖动
//        Normal <==> Pulling: 偏移值
//        用户松手
//        Pulling ==> Refreshing
//        
//        * 数据加载完了 Refreshing ==> Normal
        
        if superScollView!.dragging {
            
            if currentStatus == .Pulling && superScollView?.contentOffset.y > NormalToPullingOffset {
                //切换到Normal状态
                currentStatus = .Normal
                
            }
            
        }else if currentStatus == .Normal && superScollView?.contentOffset.y < NormalToPullingOffset {
            
            currentStatus = .Pulling
            
        }else{
            //用户松手
            // 判断当前是不是Pulling,当前是Pulling ==> Refreshing
            if currentStatus == .Pulling {
                currentStatus = .Refreshing
            }
            
        }
    }
    
    
    //MARK: - 懒加载
    
    ///箭头
   private lazy var arrowView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    ///风火轮
    private lazy var flvView :UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    
    
    ///label
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
       //设置
        label.font =  UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        label.text = "下拉刷新"
        label.sizeToFit()
       return label
    }()
    
}
